package com.luhuiguo.cms.server.handler;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import com.luhuiguo.cms.server.entity.Article;
import com.luhuiguo.cms.server.service.ArticleService;
import com.luhuiguo.cms.shared.model.ArticleModel;
import com.luhuiguo.cms.shared.rpc.RemoveDraftArticles;
import com.luhuiguo.cms.shared.rpc.RemoveDraftArticlesResult;
import com.luhuiguo.gwt.dispatcher.server.ActionHandler;
import com.luhuiguo.gwt.dispatcher.server.ExecutionContext;
import com.luhuiguo.gwt.dispatcher.shared.exception.ActionException;

@Component
public class RemoveDraftArticlesHandler implements ActionHandler<RemoveDraftArticles, RemoveDraftArticlesResult> {

    @Autowired
    private ArticleService articleService;

    @Override
    @PreAuthorize("isAuthenticated()")
    public RemoveDraftArticlesResult execute(RemoveDraftArticles action, ExecutionContext context)
            throws ActionException {

        List<Article> list = articleService.findArticlesByStatus(ArticleModel.DRAFT);

        for (Article article : list) {
            articleService.deleteArticle(article.getId());
        }

        return new RemoveDraftArticlesResult(list.size());

    }

    @Override
    public Class<RemoveDraftArticles> getActionType() {
        return RemoveDraftArticles.class;
    }

    @Override
    public void rollback(RemoveDraftArticles action, RemoveDraftArticlesResult result, ExecutionContext context)
            throws ActionException {

    }

}
